# Tauri Android Auto Build Script v2.0
# Complete build solution for Windows symlink issues

param(
    [switch]$Release,
    [switch]$SkipFrontend,
    [switch]$Verbose
)

# Set console encoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# Color output functions
function Write-ColorOutput($ForegroundColor) {
    $fc = $host.UI.RawUI.ForegroundColor
    $host.UI.RawUI.ForegroundColor = $ForegroundColor
    if ($args) {
        Write-Output $args
    }
    $host.UI.RawUI.ForegroundColor = $fc
}

function Write-Success { Write-ColorOutput Green $args }
function Write-Warning { Write-ColorOutput Yellow $args }
function Write-Error { Write-ColorOutput Red $args }
function Write-Info { Write-ColorOutput Cyan $args }

# Error handling
$ErrorActionPreference = "Stop"

try {
    Write-Info "=========================================="
    Write-Info "    Tauri Android Auto Build Script v2.0"
    Write-Info "=========================================="
    Write-Host ""

    # 1. Environment check
    Write-Info "1. Checking development environment..."
    
    # Check Rust
    try {
        $rustVersion = rustc --version 2>$null
        Write-Success "+ Rust: $rustVersion"
    } catch {
        Write-Error "- Rust not installed! Please visit https://rustup.rs/"
        exit 1
    }

    # Check Node.js
    try {
        $nodeVersion = node --version 2>$null
        Write-Success "+ Node.js: $nodeVersion"
    } catch {
        Write-Error "- Node.js not installed! Please install Node.js"
        exit 1
    }

    # Check npm
    try {
        $npmVersion = npm --version 2>$null
        Write-Success "+ npm: v$npmVersion"
    } catch {
        Write-Error "- npm not installed!"
        exit 1
    }

    Write-Host ""

    # 2. Check Android environment
    Write-Info "2. Checking Android development environment..."
    
    if (-not $env:ANDROID_HOME) {
        $androidSdk = "$env:LOCALAPPDATA\Android\Sdk"
        if (Test-Path $androidSdk) {
            $env:ANDROID_HOME = $androidSdk
            Write-Success "+ Auto-detected ANDROID_HOME: $androidSdk"
        } else {
            Write-Warning "! ANDROID_HOME not set, may affect build"
        }
    } else {
        Write-Success "+ ANDROID_HOME: $env:ANDROID_HOME"
    }

    if (-not $env:JAVA_HOME) {
        $androidStudioJdk = "$env:ANDROID_HOME\..\Android Studio\jbr"
        if (Test-Path $androidStudioJdk) {
            $env:JAVA_HOME = $androidStudioJdk
            Write-Success "+ Using Android Studio JDK: $androidStudioJdk"
        } else {
            Write-Warning "! JAVA_HOME not set, may affect build"
        }
    } else {
        Write-Success "+ JAVA_HOME: $env:JAVA_HOME"
    }

    Write-Host ""

    # 3. Add Android targets
    Write-Info "3. Configuring Rust Android targets..."
    $ErrorActionPreference = "SilentlyContinue"
    rustup target add aarch64-linux-android | Out-Null
    rustup target add armv7-linux-androideabi | Out-Null
    rustup target add i686-linux-android | Out-Null
    rustup target add x86_64-linux-android | Out-Null
    $ErrorActionPreference = "Stop"
    Write-Success "+ Android target platforms configured"

    Write-Host ""

    # 4. Install dependencies
    Write-Info "4. Installing project dependencies..."
    npm install
    if ($LASTEXITCODE -ne 0) {
        Write-Error "- npm dependencies installation failed"
        exit 1
    }
    Write-Success "+ Project dependencies installed"

    Write-Host ""

    # 5. Initialize Tauri Android
    Write-Info "5. Initializing Tauri Android..."
    if (-not (Test-Path "src-tauri\gen\android")) {
        npx tauri android init
        if ($LASTEXITCODE -ne 0) {
            Write-Error "- Tauri Android initialization failed"
            exit 1
        }
        Write-Success "+ Tauri Android initialization completed"
    } else {
        Write-Success "+ Tauri Android already initialized (skipped)"
    }

    Write-Host ""

    # 6. Build frontend
    if (-not $SkipFrontend) {
        Write-Info "6. Building frontend project..."
        npm run build
        if ($LASTEXITCODE -ne 0) {
            Write-Error "- Frontend build failed"
            exit 1
        }
        Write-Success "+ Frontend build completed"
    } else {
        Write-Warning "6. Skipping frontend build (using -SkipFrontend parameter)"
    }

    Write-Host ""

    # 7. Build Android APK
    if ($Release) {
        Write-Info "7. Building Android APK (Release)..."
    } else {
        Write-Info "7. Building Android APK (Debug)..."
    }
    
    # Use direct gradle build (more reliable than tauri android build)
    Push-Location "src-tauri\gen\android"
    try {
        if ($Release) {
            Write-Info "Running gradle assembleRelease..."
            .\gradlew-home.bat assembleRelease
            $gradleExitCode = $LASTEXITCODE
            
            # Check if APK was actually created
             $apkPath = "app\build\outputs\apk\release\app-release-unsigned.apk"
            if (Test-Path $apkPath) {
                Write-Success "+ Android Release APK build completed successfully"
                Write-Info "APK created at: $apkPath"
            } else {
                Write-Error "- Gradle release build failed: APK not found"
                exit 1
            }
        } else {
            Write-Info "Running gradle assembleDebug..."
            .\gradlew.bat assembleDebug
            $gradleExitCode = $LASTEXITCODE
            
            # Check if APK was actually created
            $apkPath = "app\build\outputs\apk\debug\app-debug.apk"
            if (Test-Path $apkPath) {
                Write-Success "+ Android Debug APK build completed successfully"
                Write-Info "APK created at: $apkPath"
            } else {
                Write-Error "- Gradle debug build failed: APK not found"
                exit 1
            }
        }
    } finally {
        Pop-Location
    }

    Write-Host ""

    # 8. Check build results
    Write-Info "8. Checking build results..."
    
    $apkFiles = @()
    if (Test-Path "lottery-calculator-debug.apk") {
        $apkFiles += "lottery-calculator-debug.apk"
    }
    if (Test-Path "lottery-calculator.apk") {
        $apkFiles += "lottery-calculator.apk"
    }
    
    # Find other APK files
    $foundApks = Get-ChildItem -Path "src-tauri\gen\android" -Recurse -Filter "*.apk" -ErrorAction SilentlyContinue
    foreach ($apk in $foundApks) {
        $targetName = if ($Release) { "lottery-calculator-release.apk" } else { "lottery-calculator-debug.apk" }
        Copy-Item -Path $apk.FullName -Destination $targetName -Force
        $apkFiles += $targetName
    }

    Write-Host ""
    Write-Info "=========================================="
    Write-Success "    Android APK Build Successful!"
    Write-Info "=========================================="
    Write-Host ""

    if ($apkFiles.Count -gt 0) {
        Write-Info "Generated files:"
        foreach ($apk in $apkFiles) {
            $size = [math]::Round((Get-Item $apk).Length / 1MB, 2)
            Write-Success "  + $apk ($size MB)"
        }
    } else {
        Write-Warning "! No generated APK files found"
    }

    Write-Host ""
    Write-Info "....."
    Write-Host ""

} catch {
    Write-Error "Build failed: $($_.Exception.Message)"
    exit 1
}